package com.team.sion.service.Impl;

import com.team.sion.mapper.RankListMapper;
import com.team.sion.pojo.RankList;
import com.team.sion.pojo.RankListExample;
import com.team.sion.service.RankListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RankListServiceImpl implements RankListService {
    @Autowired
    private RankListMapper rankListMapper;

    @Override
    public void setRank(RankList rankList) {
        RankListExample rankListExample = new RankListExample();
        rankListExample.createCriteria().andUserIdEqualTo(rankList.getUserId()).andSonglistIdEqualTo(rankList.getSongListId());
        List<RankList> rankLists = rankListMapper.selectByExample(rankListExample);
        if(rankLists.size()>0){
            rankListMapper.deleteByExample(rankListExample);
        }
        rankListMapper.insertSelective(rankList);
    }

    @Override
    public Integer getRank(Integer songListId) {
        RankListExample rankListExample = new RankListExample();
        rankListExample.createCriteria().andSonglistIdEqualTo(songListId);
        List<RankList> list = rankListMapper.selectByExample(rankListExample);
        if(list.size() == 0) return 0;
        Integer sum = 0;
        for(RankList rank : list){
            sum += rank.getScore();
        }
        return sum / list.size();
    }

    @Override
    public Integer getUserRank(Integer consumerId, Integer songListId) {
        RankListExample rankListExample = new RankListExample();
        rankListExample.createCriteria().andUserIdEqualTo(consumerId).andSonglistIdEqualTo(songListId);
        List<RankList> list = rankListMapper.selectByExample(rankListExample);
        if(list.size() == 0) return null;
        return list.get(0).getScore();
    }
}
